﻿// SSHProjectTest.cpp : Defines the entry point for the application.
//

#include "SSHProjectTest.h"

#include "Sftp.h"
#include "Shell.h"

#define FDLOG(x) (LocalRollLogger::getInstance()->logger(x)->any())
#define LOG_MAIN_DEBUG FDLOG("SSHProjectTest_main.txt") << FILE_FUNC_LINE << "|"

using namespace std;

static int socket_connect(const char* hostname, int port) {
    int sock;
#ifdef _WIN32
    WSADATA wsaData;
    if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) {
        printf("Failed to initialize Winsock\n");
        return -1;
    }
#endif

    struct sockaddr_in server_addr;

    // 创建一个socket
    sock = socket(AF_INET, SOCK_STREAM, 0);
    if (sock < 0) {
#ifdef _WIN32
        printf("Failed to create socket. Error code: %d\n", WSAGetLastError());
#else
        perror("Failed to create socket");
#endif
        return -1;
    }

    // 设置服务器地址
    memset(&server_addr, 0, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(port);
    if (inet_pton(AF_INET, hostname, &server_addr.sin_addr) <= 0) {
#ifdef _WIN32
        printf("Invalid address/ Address not supported\n");
#else
        perror("Failed to convert hostname to IP address");
#endif
        close(sock);
        return -1;
    }

    // 建立连接
    if (connect(sock, (struct sockaddr*)&server_addr, sizeof(server_addr)) < 0) {
#ifdef _WIN32
        printf("Connection Failed. Error code: %d\n", WSAGetLastError());
#else
        perror("Failed to connect to remote host");
#endif
        close(sock);
        return -1;
    }

    return sock;
}

int main(int argc, char* argv[])
{
	/*
	cout << "Hello CMake." << endl;
	LOG_MAIN_DEBUG << "Hello CMake." << endl;
	nsshell::network::Shell shell;
	//shell.execute(argc, argv);

	//sftp
	//下面的代码只要在进程初始化的时候执行
	nssftp::network::SFTP_Init();

	//测试SFTP链接
	nssftp::network::SFTP_Libssh2* client = nssftp::network::SFTP_Libssh2::Inst();
	std::string ip = "192.168.100.128";
	uint16_t port = 22;
	std::string usr = "root";
	std::string pwd = "root";
	if (false == client->IsAbilityConn(ip, port, usr, pwd))
	{
		std::cout << client->strLastError << std::endl;
		return -1;
	}

	//测试文件上传,d:\\temp\\a.html
	if (0 != client->upload(ip, 22, usr, pwd, "D:\\Snipaste_2024-01-28_00-51-52.png", "/root/Snipaste_2024-01-28_00-51-52.png"))
	{
		std::cout << "Error:" << client->strLastError << std::endl;
	}
	else
	{
		std::cout << client->strLastError << std::endl;
	}

	int input;
	std::cin >> input;

	//测试文件下载
	if (0 != client->download(ip, 22, usr, pwd, "/root/Snipaste_2024-01-28_00-51-52.png", "D:\\Snipaste_2024-01-28_00-51-52.png"))
	{
		std::cout << "Error:" << client->strLastError << std::endl;
	}
	else
	{
		std::cout << client->strLastError << std::endl;
	}

	//进程准备结束，释放资源的时候，运行下面的代码
	nssftp::network::SFTP_Exit();
	*/
    // 初始化libssh2库
    int rc = libssh2_init(0);
    if (rc != 0) {
        fprintf(stderr, "Failed to initialize libssh2. Error code %d", rc);
            return 1;
    }

    // 创建SSH会话
    LIBSSH2_SESSION* session;
    session = libssh2_session_init();
    if (session == NULL) {
        fprintf(stderr, "Failed to create session");
            return 1;
    }

    // 设置会话阻塞模式
    libssh2_session_set_blocking(session, 1);

    // 建立连接
    const char* hostname = "192.168.100.128";
    const int port = 22;
    const char* username = "root";
    const char* password = "root";
    int socket = socket_connect(hostname, port); // 自定义函数，用于建立socket连接
    if (socket < 0) {
        fprintf(stderr, "Failed to connect to the remote host");
            return 1;
    }

    rc = libssh2_session_handshake(session, socket);
    if (rc != 0) {
        fprintf(stderr, "Session handshake failed");
            return 1;
    }

    rc = libssh2_userauth_password(session, username, password);
    if (rc != 0) {
        fprintf(stderr, "Authentication failed");
            return 1;
    }



    do
    {
        // 执行远程命令
        LIBSSH2_CHANNEL* channel = libssh2_channel_open_session(session);
        if (channel == NULL) {
            fprintf(stderr, "Failed to open a channel");
            return 1;
        }
        std::string execmd;
        std::cin >> execmd;
        std::cout << "execmd:" << execmd << std::endl;
        rc = libssh2_channel_exec(channel, execmd.c_str());
        if (rc != 0) {
            fprintf(stderr, "Failed to execute remote command");
            return 1;
        }

        // 读取并打印远程命令输出
        char buffer[1024];
        int nbytes;
        while ((nbytes = libssh2_channel_read(channel, buffer, sizeof(buffer) - 1)) > 0) {
            buffer[nbytes] = '\0';
            printf("%s", buffer);
        }
        // 断开连接和清理
        libssh2_channel_close(channel);
        libssh2_channel_free(channel);
    } while (1);

    libssh2_session_disconnect(session, "Goodbye");
    libssh2_session_free(session);
    libssh2_exit();
	return 0;
}
